<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', 
				'actions'=>array('profile','balance','balanceinfo','payment','removeimage','exercises'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Profile of user
	 * @author K.D
	 */
	public function actionProfile()
	{
	  $model = $this->loadModel();
		$pass = $model->password;
		$old = $model->password;
		$model->password = '';
		$profile = UserProfile::model()->findByAttributes(array('userID'=>Yii::app()->user->id));
		if(!empty($profile)) {
		  if($profile->dateofbirth != '')
				$profile->dateofbirth = date("d-m-Y",$profile->dateofbirth);
		}
    $file_avatar = UserProfile::model()->getAvatar(Yii::app()->user->id);
    $img_avatar = "";
    if(isset($_POST['User']) && isset($_POST['UserProfile'])) {
      $model->attributes=$_POST['User'];
			$profile->attributes=$_POST['UserProfile'];
			$model->setScenario('update_profile');
			$validate1 = $model->validate();
			$validate2 = $profile->validate();
			
			if($validate1 && $validate2){
			  if($_POST['User']['password']!='') {
					$model->password = md5($_POST['User']['password']);
				}					
				if($_POST['UserProfile']['dateofbirth']!='') {						 
					$profile->dateofbirth = strtotime($_POST['UserProfile']['dateofbirth']);		
				}
				if($model->save(false)) {
					if(CUploadedFile::getInstanceByName('UserProfile[avatar]')) { 
					  if(!empty($file_avatar)) {
					    $f = File::model()->findByAttributes(array('filesaved'=>$file_avatar));
  					  if(!empty($f)) {
      	        if(file_exists(Yii::app()->basePath.'/../upload/avatar/'.$file_avatar)) {
      	          @unlink(Yii::getPathOfAlias("webroot").'/upload/avatar/'.$file_avatar);
      	        }
      	        if(file_exists(Yii::app()->basePath.'/../upload/avatar/thumbs_70x70/'.$file_avatar)) {
      	          @unlink(Yii::getPathOfAlias("webroot").'/upload/avatar/thumbs_70x70/'.$file_avatar);
      	        }
      	        $f->delete();
      	      }					    
					  }
						$avatar = new File();
						$photo = CUploadedFile::getInstanceByName('UserProfile[avatar]');
						$avatar->filename = $photo->getName();
			    	$avatar->filesaved = encodeFilename(time().'_'.$photo->getName());
			    	$avatar->filetype =  $photo->getType();
			    	$avatar->folder = 'avatar';
			    	$photo->saveAs('upload/avatar/'.$avatar->filesaved);
			    	$avatar->save();
			    	$profile->avatar = $avatar->ID;
			    	//thumbnail 
			    	$thumb = Yii::app()->image->load(Yii::getPathOfAlias("webroot")."/upload/avatar/".$avatar->filesaved);
            $thumb->resize(70, 70);
            $thumb->save(Yii::getPathOfAlias("webroot")."/upload/avatar/thumbs_70x70/".$avatar->filesaved);//save vao thumb
					}
					
					// save user profile
					$profile->save(false);
					
					Yii::app()->user->setFlash('success',"Cập nhật thành công");
					unset($_POST);
				}
			}
    }
    if(!empty($file_avatar)) {
      $img_avatar = Yii::app()->baseUrl."/upload/avatar/thumbs_70x70/".$file_avatar;
    }
		$this->render('profile',array(
			'model'=>$model, 'profile'=>$profile, 'img_avatar'=>$img_avatar
		));
	}
  /**
   * Remove image of avatar
   * @author K.D
   */
	public function actionRemoveImage() {
	  if(Yii::app()->request->isAjaxRequest) {
	    $ID = isset($_POST['ID'])?$_POST['ID']:"";
	    $profile= UserProfile::model()->findByPk($ID);
	    if(!empty($profile)) {
	      $file = File::model()->findByPk($profile->avatar);
	      if(!empty($file)) {
	        if(file_exists(Yii::app()->basePath.'/../upload/avatar/'.$file->filesaved)) {
	          @unlink(Yii::getPathOfAlias("webroot").'/upload/avatar/'.$file->filesaved);
	        }
	        if(file_exists(Yii::app()->basePath.'/../upload/avatar/thumbs_70x70/'.$file->filesaved)) {
	          @unlink(Yii::getPathOfAlias("webroot").'/upload/avatar/thumbs_70x70/'.$file->filesaved);
	        }
	        $file->delete();
	      }
	      $profile->avatar = "";
	      $profile->update();
	      
	      echo "success";
	    }
	  }
	}
	
	/**
	 * Balance + payment of user 
	 * @author K.D
	 */
  public function actionBalance()
  {
    $model = new UserPayment();
    //$model->money = 10000;
    if(isset($_POST['UserPayment'])) {
      $money = $_POST['UserPayment']['money'];
      $model->userID = Yii::app()->user->id;
      $model->money = $money;
      $model->status = 1;
      $model->description = 'Nạp '.$money.' VND';
      $model->datetime = time();
      $model->save(false);
      
      if($_POST['promotion']!=0) {
        $promo = ($money*$_POST['promotion'])/100;
        $model = new UserPayment();
        $model->userID = Yii::app()->user->id;
        $model->money = $promo;
        $model->status = 3;
        $model->description = 'Khuyến mãi '.$promo.' VND';
        $model->datetime = time();
        $model->save(false);
      }
      
      $balance = UserBalance::model()->findByAttributes(array('userID'=>Yii::app()->user->id));
      if(empty($balance)) {
        $balance = new UserBalance();
        $balance->userID = Yii::app()->user->id;
        $balance->balance = UserBalance::model()->checkBalance(Yii::app()->user->id, 1, 2);
        $balance->promotion = UserBalance::model()->checkBalance(Yii::app()->user->id, 3, 4);
        $balance->save(false);
      }
      else {
        $balance->balance = UserBalance::model()->checkBalance(Yii::app()->user->id, 1, 2);
        $balance->promotion = UserBalance::model()->checkBalance(Yii::app()->user->id, 3, 4);
        $balance->update();
      }
      print json_encode(array('result'=>array('success'=>'Nạp tiền thành công')));
			die;
    }
    $this->render('balance', array(
      'model'=>$model,
    ));
  }
  
	/**
	 * @author K.D
	 * Balance information of user
	 */
  public function actionBalanceInfo()
  {
    $balance = UserBalance::model()->getBalance(Yii::app()->user->id);
    $promotion = UserBalance::model()->getPromotion(Yii::app()->user->id);
    $this->renderPartial('balanceinfo', array(
      'balance'=>$balance, 'promotion'=>$promotion
    ));
  }
/**
	 * @author K.D
	 * Payment history of user
	 */
  public function actionPayment()
  {
    $model = new UserPayment('search');
    $this->renderPartial('payment', array(
      'model'=>$model
    ), false, true);
  }
  
  /**
   * List all exercises of user
   */
  public function actionExercises()
  {
    $model=new Issue('getIssues');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Issue']))
			$model->attributes=$_GET['Issue'];

			
		
		$answer=new Answer('getAnswers');
		$answer->unsetAttributes();  // clear any default values
		if(isset($_GET['Answer']))
			$answer->attributes=$_GET['Answer'];
			
			
		$this->render('exercises',array(
			'model'=>$model,'answer'=>$answer,
		));
  
  }
  
  
  
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel()
	{ 
		$model=User::model()->findByAttributes(array('ID'=>Yii::app()->user->id,'deleted'=>0,'active'=>1));
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
